<?php
class Other_IO extends QDB_ActiveRecord_Abstract
{
	/**
	 * 返回对象的定义
	 *
	 * @static
	 *
	 * @return array
	 */
	static function __define()
	{
		return array
		(
			// 指定该 ActiveRecord 要使用的行为插件
			'behaviors' => '',

			// 指定行为插件的配置
			'behaviors_settings' => array
			(
			    # '插件名' => array('选项' => 设置),
			),

			// 用什么数据表保存对象
			'table_name' => 'other_io',

			// 指定数据表记录字段与对象属性之间的映射关系
			// 没有在此处指定的属性，QeePHP 会自动设置将属性映射为对象的可读写属性
			'props' => array
			(
				// 主键应该是只读，确保领域对象的“不变量”
				'id' => array('readonly' => true),

				/**
				 *  可以在此添加其他属性的设置
				 */
				# 'other_prop' => array('readonly' => true),

				/**
				 * 添加对象间的关联
				 */
				# 'other' => array('has_one' => 'Class'),

			),

			/**
			 * 允许使用 mass-assignment 方式赋值的属性
			 *
			 * 如果指定了 attr_accessible，则忽略 attr_protected 的设置。
			 */
			'attr_accessible' => '',

			/**
			 * 拒绝使用 mass-assignment 方式赋值的属性
			 */
			'attr_protected' => 'id',

			/**
			 * 指定在数据库中创建对象时，哪些属性的值不允许由外部提供
			 *
			 * 这里指定的属性会在创建记录时被过滤掉，从而让数据库自行填充值。
			 */
			'create_reject' => '',

			/**
			 * 指定更新数据库中的对象时，哪些属性的值不允许由外部提供
			 */
			'update_reject' => '',

			/**
			 * 指定在数据库中创建对象时，哪些属性的值由下面指定的内容进行覆盖
			 *
			 * 如果填充值为 self::AUTOFILL_TIMESTAMP 或 self::AUTOFILL_DATETIME，
			 * 则会根据属性的类型来自动填充当前时间（整数或字符串）。
			 *
			 * 如果填充值为一个数组，则假定为 callback 方法。
			 */
			'create_autofill' => array
			(
				# 属性名 => 填充值
				# 'is_locked' => 0,
			),

			/**
			 * 指定更新数据库中的对象时，哪些属性的值由下面指定的内容进行覆盖
			 *
			 * 填充值的指定规则同 create_autofill
			 */
			'update_autofill' => array
			(
			),

			/**
			 * 在保存对象时，会按照下面指定的验证规则进行验证。验证失败会抛出异常。
			 *
			 * 除了在保存时自动验证，还可以通过对象的 ::meta()->validate() 方法对数组数据进行验证。
			 *
			 * 如果需要添加一个自定义验证，应该写成
			 *
			 * 'title' => array(
			 *	array(array(__CLASS__, 'checkTitle'), '标题不能为空'),
			 * )
			 *
			 * 然后在该类中添加 checkTitle() 方法。函数原型如下：
			 *
			 * static function checkTitle($title)
			 *
			 * 该方法返回 true 表示通过验证。
			 */
			'validations' => array
			(
			),
		);
	}


/* ------------------ 以下是自动生成的代码，不能修改 ------------------ */

	/**
	 * 开启一个查询，查找符合条件的对象或对象集合
	 *
	 * @static
	 *
	 * @return QDB_Select
	 */
	static function find()
	{
		$args = func_get_args();
		return QDB_ActiveRecord_Meta::instance(__CLASS__)->findByArgs($args);
	}

	/**
	 * 返回当前 ActiveRecord 类的元数据对象
	 *
	 * @static
	 *
	 * @return QDB_ActiveRecord_Meta
	 */
	static function meta()
	{
		return QDB_ActiveRecord_Meta::instance(__CLASS__);
	}


/* ------------------ 以上是自动生成的代码，不能修改 ------------------ */
	/**
	 * 创建入库单
	 * @param $other_in 入库单信息
	 */
	static function createOtherIn($other_in)
	{
		$generate_result = Number_Rules::generate('other_io', 'QTRK');
		if ($generate_result['ack'] == SUCCESS)
		{
			$other_in_order = new Other_IO();
			$other_in_order->number = $generate_result['number'];
			$other_in_order->type = Q::ini('custom_flag/other_io_type/in/value');
			$other_in_order->warehouse_id = $other_in['warehouse_id'];
			$other_in_order->user_id = $other_in['user_id'];
			$other_in_order->create_time = CURRENT_DATETIME;
			$other_in_order->notes = $other_in['notes'];
			$other_in_order->save();
			$other_in_id = mysql_insert_id();
			Other_IO_Item::update($other_in['item'], $other_in_id, $other_in_order['type']);
			return array('ack' => SUCCESS, 'message' => '', 'other_io_id' => $other_in_id);
		}
		else
		{
			return array('ack' => FAILURE, 'message' => 'cannot create number');
		}
	}
	
	/**
	 * 创建出库单
	 * @param $other_in 出库单信息
	 */
	static function createOtherOut($other_out)
	{
		$generate_result = Number_Rules::generate('other_io', 'QTCK');
		if ($generate_result['ack'] == SUCCESS)
		{
			$other_out_order = new Other_IO();
			$other_out_order->number = $generate_result['number'];
			$other_out_order->type = Q::ini('custom_flag/other_io_type/out/value');
			$other_out_order->warehouse_id = $other_out['warehouse_id'];
			$other_out_order->user_id = $other_out['user_id'];
			$other_out_order->create_time = CURRENT_DATETIME;
			$other_out_order->notes = $other_out['notes'];
			$other_out_order->save();
			$other_out_id = mysql_insert_id();
			Other_IO_Item::update($other_out['item'], $other_out_id, $other_out_order['type']);
			return array('ack' => SUCCESS, 'message' => '', 'other_io_id' => $other_out_id);
		}
		else
		{
			return array('ack' => FAILURE, 'message' => 'cannot create number');
		}
	}
	
	/**
	 * 修改入库单信息
	 * @param $other_io 入库单信息
	 */
	static function editOtherIn($other_in)
	{
		$judge_result = Other_IO::judgeEditOtherIO($other_in['id']);
		if ($judge_result['ack'] == SUCCESS)
		{
			$other_io = Other_IO::find('id=?', $other_in['id'])->getOne();
			$other_io->user_id = $other_in['user_id'];
			$other_io->warehouse_id = $other_in['warehouse_id'];
			$other_io->notes = $other_in['notes'];
			$other_io->save();
			Other_IO_Item::update($other_in['item'], $other_in['id'], $other_io['type']);
			return array('ack' => SUCCESS, 'message' => '');
		}
		else
		{
			return array('ack' => FAILURE, 'message' => $judge_result['message']);
		}
	}
	
	/**
	 * 修改出库单信息
	 * @param $other_out 出库单信息
	 */
	static function editOtherOut($other_out)
	{
		$judge_result = Other_IO::judgeEditOtherOut($other_out);
		if ($judge_result['ack'] == SUCCESS)
		{
			$other_io = Other_IO::find('id=?', $other_out['id'])->getOne();
			$other_io->user_id = $other_out['user_id'];
			$other_io->warehouse_id = $other_out['warehouse_id'];
			$other_io->notes = $other_out['notes'];
			$other_io->save();
			Other_IO_Item::update($other_out['item'], $other_out['id'], $other_io['type']);
			return array('ack' => SUCCESS, 'message' => '');
		}
		else
		{
			return array('ack' => FAILURE, 'message' => $judge_result['message']);
		}
	}
	
	/**
	 * 判断入库单是否能够修改产品信息
	 * @param $other_io_id 入库单id
	 */
	static function judgeEditOtherIO($other_io_id)
	{
		$other_io = Other_IO::find('id=?', $other_io_id)->asArray()->getOne();
		if ($other_io)
		{
			if ($other_io['finance_audit'] == Q::ini('custom_flag/other_io_finance_audit/unaudited/value') && $other_io['storage_audit'] == Q::ini('custom_flag/other_io_storage_audit/unaudited/value'))
			{
				return array('ack' => SUCCESS, 'message' => '');
			}
			else
			{
				return array('ack' => FAILURE, 'message' => 'other_io have audited!');
			}
		}
		else
		{
			return array('ack' => FAILURE, 'message' => 'other_io is not exist!');
		}
	}
	
	/**
	 * 判断出库单是否能满足编辑条件
	 * @param $other_out 出库信息
	 */
	static function judgeEditOtherOut($other_out)
	{
		$check_in_db = Other_IO::find('id=?', $other_out['id'])->asArray()->getOne();
		if ($check_in_db)
		{
			if ($check_in_db['type'] == Q::ini('custom_flag/other_io_type/out/value')
					&& $check_in_db['finance_audit'] == Q::ini('custom_flag/other_io_finance_audit/unaudited/value')
					&& $check_in_db['storage_audit'] == Q::ini('custom_flag/other_io_storage_audit/unaudited/value'))
			{
				if ($other_out['item'])
				{
					$other_out_product = $result = array();
					foreach ($other_out['item'] as $ooi)
					{
						if ( ! array_key_exists($ooi['product_basic_id'], $other_out_product))
						{
							$product_warehouse = Product_Warehouse::find('warehouse_id=? and product_basic_id=?', $other_out['warehouse_id'], $ooi['product_basic_id'])->asArray()->getOne();
							$already_use = Other_IO_Item::find('other_io_id=? and product_basic_id=?', $other_out['id'], $ooi['product_basic_id'])->getSum('quantity');
							$other_out_product[$ooi['product_basic_id']]['available_quantity'] = $product_warehouse['available_quantity'] + $already_use;
							$other_out_product[$ooi['product_basic_id']]['need_quantity'] = 0;
						}
						$other_out_product[$ooi['product_basic_id']]['need_quantity'] += $ooi['quantity'];
					}
					$result['ack'] = SUCCESS;
					foreach ($other_out_product as $k => $dp)
					{
						if ($dp['need_quantity'] > $dp['available_quantity'])
						{
							$result['ack'] = FAILURE;
							$result['message'] = $k . 'available quantity not enough';
						}
						if ($dp['need_quantity'] < 0)
						{
							$result['ack'] = FAILURE;
							$result['message'] = $k . 'quantity is negative:'.$dp['need_quantity'];
						}
					}
					return $result;
				}
				else
				{
					return array('ack' => SUCCESS, 'message' => '');
				}
			}
			else
			{
				return array('ack' => FAILURE, 'message' => 'other out cannot edit');
			}
		}
		else
		{
			return array('ack' => FAILURE, 'message' => 'other out not exists');
		}
	}

	/**
	 * 仓库审核入库
	 * @param $other_oi_id 入库单id
	 */
	static function inStorageAudit($other_in_id)
	{
		$default_currency = Currency::getDefaultCurrency();
		$judge_result = Other_IO::judgeStorageAudit($other_in_id, Q::ini('custom_flag/other_io_type/in/value'));
		if ($judge_result['ack'] == SUCCESS)
		{
			$other_in = Other_IO::find('id=?', $other_in_id)->getOne();
			$other_in->storage_audit = Q::ini('custom_flag/other_io_storage_audit/audited/value');
			$other_in->storage_audit_user_id = CURRENT_USER_ID;
			$other_in->storage_audit_time = CURRENT_DATETIME;
			$other_in->save();
			$item = Other_IO_Item::find('other_io_id=?', $other_in_id)->asArray()->getAll();
			foreach ($item as $i)
			{
				$log = new Inventory_Log();
				$log->product_basic_id = $i['product_basic_id'];
				$log->warehouse_id = $other_in['warehouse_id'];
				$log->type = Q::ini('custom_flag/inventory_log_type/other_in/value');
				$log->relate_table_id = $i['id'];
				$log->init_quantity = 0;
				$log->in_quantity = $i['quantity'];
				$log->out_quantity = 0;
				$log->cost_price = $i['cost_price'];
				$log->sales_price = 0;
				$log->cost_amount = $i['quantity'] * $i['cost_price'];
				$log->sales_amount = 0;
				$log->currency_rate = $default_currency['rate'];
				$log->currency_id = $default_currency['id'];
				$log->remaining_quantity = $i['quantity'];
				$log->user_id = CURRENT_USER_ID;
				$log->time = CURRENT_DATETIME;
				$log->save();
				Product_Warehouse::actualQuantityIncrease(0, $i['product_basic_id'], $other_in['warehouse_id'], $i['quantity']);
				Product_Warehouse::availableQuantityIncrease(0, $i['product_basic_id'], $other_in['warehouse_id'], $i['quantity']);
			}
			return array('ack' => SUCCESS, 'message' => '');
		}
		else
		{
			return array('ack' => FAILURE, 'message' => $judge_result['message']);
		}
	}
	
	/**
	 * 仓库审核出库
	 * @param $other_oi_id 出库单id
	 */
	static function outStorageAudit($other_out_id)
	{
		$default_currency = Currency::getDefaultCurrency();
		$judge_result = Other_IO::judgeStorageAudit($other_out_id, Q::ini('custom_flag/other_io_type/out/value'));
		if ($judge_result['ack'] == SUCCESS)
		{
			$other_out = Other_IO::find('id=?', $other_out_id)->getOne();
			$other_out->storage_audit = Q::ini('custom_flag/other_io_storage_audit/audited/value');
			$other_out->storage_audit_user_id = CURRENT_USER_ID;
			$other_out->storage_audit_time = CURRENT_DATETIME;
			$other_out->save();
			$item = Other_IO_Item::find('other_io_id=?', $other_out_id)->asArray()->getAll();
			foreach ($item as $i)
			{
				if ($i['quantity'] > 0)
				{
					$cost_amount = Inventory_Log::getCostAmountByFIFO($i['product_basic_id'], $other_out['warehouse_id'], $i['quantity']);
					$log = new Inventory_Log();
					$log->product_basic_id = $i['product_basic_id'];
					$log->warehouse_id = $other_out['warehouse_id'];
					$log->type = Q::ini('custom_flag/inventory_log_type/other_out/value');
					$log->relate_table_id = $i['id'];
					$log->init_quantity = 0;
					$log->in_quantity = 0;
					$log->out_quantity = $i['quantity'];
					$log->cost_price = $cost_amount['cost_amount']/$i['quantity'];
					$log->sales_price = 0;
					$log->cost_amount = $cost_amount['cost_amount'];
					$log->sales_amount = 0;
					$log->currency_rate = $default_currency['rate'];
					$log->currency_id = $default_currency['id'];
					$log->remaining_quantity = 0;
					$log->user_id = CURRENT_USER_ID;
					$log->time = CURRENT_DATETIME;
					$log->save();
					QDB::getConn()->execute('update other_io_item set cost_price='.($cost_amount['cost_amount']/$i['quantity']).' where id='.$i['id']);
					Product_Warehouse::actualQuantityDecrease(0, $i['product_basic_id'], $other_out['warehouse_id'], $i['quantity']);
				}
			}
			return array('ack' => SUCCESS, 'message' => '');
		}
		else
		{
			return array('ack' => FAILURE, 'message' => $judge_result['message']);
		}
	}
	
	/**
	 * 财务审核
	 * @param $ids 其他出入库单id
	 */
	static function financeAudit($ids)
	{
		$message = array();
		foreach ($ids as $key => $id)
		{
			$judge_result = Other_IO::judgeFinanceAudit($id);
			if ($judge_result['ack'] == SUCCESS)
			{
				QDB::getConn()->execute('update other_io set finance_audit=' . Q::ini('custom_flag/other_io_finance_audit/audited/value') . ',finance_audit_user_id=' . CURRENT_USER_ID . ',finance_audit_time=\'' . CURRENT_DATETIME . '\' where id=' . $id);
			}
			else
			{
				$message[] = 'No.' . ($key + 1) . ' ' . $judge_result['message'];
			}
		}
		if ($message)
		{
			return array('ack' => FAILURE, 'message' => implode(',', $message));
		}
		else
		{
			return array('ack' => SUCCESS, 'message' => '');
		}
	}
	
	/**
	 * 判断是否可以财务审核
	 * @param $other_io_id 入库/出库单id
	 */	
	static function judgeFinanceAudit($other_io_id)
	{
		$other_io = Other_IO::find('id=?', $other_io_id)->asArray()->getOne();
		if ($other_io)
		{
			if ($other_io['finance_audit'] == Q::ini('custom_flag/other_io_finance_audit/unaudited/value'))
			{
				return array('ack' => SUCCESS, 'message' => '');
			}
			else
			{
				return array('ack' => FAILURE, 'message' => 'other_io have audited!');
			}
		}
		else
		{
			return array('ack' => FAILURE, 'message' => 'other_io is not exist!');
		}
	}
	
	/**
	 * 计算其他出入库的成本
	 * @param $other_io
	 */
	static function calculateCostAmount(&$other_io)
	{
		foreach ($other_io as $k => $oi)
		{
			$cost_amount = $other_io[$k]['cost_amount'] = 0;
			$other_io_item = Other_IO_Item::find('other_io_id=?', $oi['id'])->asArray()->getAll();
			foreach ($other_io_item as $oii)
			{
				$cost_amount += $oii['cost_price'] * $oii['quantity'];
			}
			$other_io[$k]['cost_amount'] = $cost_amount;
		}
		return $other_io;
	}
	
	/**
	 * 判断是否可以仓库审核
	 * @param $other_io_id 入库/出库单id
	 */
	static function judgeStorageAudit($other_io_id, $type)
	{
		$other_io = Other_IO::find('id=?', $other_io_id)->asArray()->getOne();
		if ($other_io)
		{
			if ($other_io['storage_audit'] == Q::ini('custom_flag/other_io_storage_audit/unaudited/value'))
			{
				if ($other_io['type'] == $type)
				{
					return array('ack' => SUCCESS, 'message' => '');
				}
				else
				{
					return array('ack' => FAILURE, 'message' => 'other_io type is incorrect!');
				}
			}
			else
			{
				return array('ack' => FAILURE, 'message' => 'other_io have audited!');
			}
		}
		else
		{
			return array('ack' => FAILURE, 'message' => 'other_io is not exist!');
		}
	}
	
	/**
	 * 按条件搜索入库单
	 * @param $condition 条件
	 * @param $cp 当前页
	 * @param $ps 每页大小
	 */
	static function search($condition, $cp, $ps)
	{
		$where = Other_IO::buildSearchWhere($condition);
		$columns = array(
				'other_io.*',
				'user.name as user_name',
				'warehouse.name as warehouse_name'
		);
		if ($cp == 0 && $ps == 0)
		{
			$select = Other_IO::find($where)
				->joinLeft('user', '', 'user.id=other_io.user_id')
				->joinLeft('warehouse', '', 'warehouse.id=other_io.warehouse_id')
				->order('other_io.id desc')->setColumns();
			$pagination = array();
		}
		else
		{
			$select = Other_IO::find($where)
				->joinLeft('user', '', 'user.id=other_io.user_id')
				->joinLeft('warehouse', '', 'warehouse.id=other_io.warehouse_id')
				->order('other_io.id desc')->setColumns($columns)->limitPage($cp, $ps);
			$pagination = $select->getPagination();
		}
		$other_io = $select->asArray()->getAll();
		return array(
				'ack' => SUCCESS,
				'message' => '',
				'data' => $other_io,
				'pagination' => $pagination
		);
	}
	
	/**
	 * 组装搜索条件
	 * @param $condition 条件数组
	 */
	static function buildSearchWhere($condition)
	{
		$where = '1';
		if ( ! empty($condition['begin_create_time']))
		{
			$where .= ' and other_io.create_time>=\'' . $condition['begin_create_time'] . '\'';
		}
		if ( ! empty($condition['end_create_time']))
		{
			$where .= ' and other_io.create_time<=\'' . $condition['end_create_time'] . ' 23:59:59\'';
		}
		if ( ! empty($condition['begin_finance_audit_time']))
		{
			$where .= ' and other_io.finance_audit_time>=\'' . $condition['begin_finance_audit_time'] . '\'';
		}
		if ( ! empty($condition['end_finance_audit_time']))
		{
			$where .= ' and other_io.finance_audit_time<=\'' . $condition['end_finance_audit_time'] . ' 23:59:59\'';
		}
		if ( ! empty($condition['begin_storage_audit_time']))
		{
			$where .= ' and other_io.storage_audit_time>=\'' . $condition['begin_storage_audit_time'] . '\'';
		}
		if ( ! empty($condition['end_storage_audit_time']))
		{
			$where .= ' and other_io.storage_audit_time<=\'' . $condition['end_storage_audit_time'] . ' 23:59:59\'';
		}
		if ( ! empty($condition['number']))
		{
			$where .= ' and other_io.number=\'' . $condition['number'] . '\'';
		}
		if ( ! empty($condition['warehouse_id']))
		{
			$where .= ' and other_io.warehouse_id=' . $condition['warehouse_id'];
		}
		if ( ! empty($condition['product']))
		{
			$item = Other_IO_Item::find('product_basic.number=? or product_basic.name like ?', $condition['product'], '%'.$condition['product'].'%')
				->joinLeft('product_basic', '', 'product_basic.id=other_io_item.product_basic_id')
				->asArray()->getAll();
			if ($item)
			{
				$io_ids = array();
				foreach ($item as $i)
				{
					$io_ids[] = $i['other_io_id'];
				}
				$where .= ' and other_io.id in (' . implode(',', $io_ids) . ')';
			}
			else
			{
				$where .= ' and other_io.id = 0';
			}
		}
		if ( ! empty($condition['finance_audit']))
		{
			$finance_audit_filter = '0';
			foreach (Q::ini('custom_flag/other_io_finance_audit') as $o)
			{
				if (isset($condition['finance_audit'][$o['value']]) && $condition['finance_audit'][$o['value']] == $o['value'])
				{
					$finance_audit_filter .= ' or other_io.finance_audit=' . $o['value'];
				}
			}
			$where .= ' and (' . $finance_audit_filter . ')';
		}
		if ( ! empty($condition['storage_audit']))
		{
			$storage_audit_filter = '0';
			foreach (Q::ini('custom_flag/other_io_storage_audit') as $sa)
			{
				if (isset($condition['storage_audit'][$sa['value']]) && $condition['storage_audit'][$sa['value']] == $sa['value'])
				{
					$storage_audit_filter .= ' or other_io.storage_audit=' . $sa['value'];
				}
			}
			$where .= ' and (' . $storage_audit_filter . ')';
		}
		if (isset($condition['type']))
		{
			$where .=' and other_io.type=\''.$condition['type'].'\'';
		}
		return $where;
	}
}